package com.usian.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.sun.org.apache.regexp.internal.RE;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.search.dtos.UserSearchDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.search.feign.BehaviorFeign;
import com.usian.search.service.ApUserSearchService;
import com.usian.search.service.ArticleSearchService;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private ApUserSearchService apUserSearchService;

    @Autowired
    private BehaviorFeign behaviorFeign;

    @Override
    public ResponseResult search(UserSearchDto dto) {

        try {
            if (dto==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"参数不存在");
            }

            /*检索的时候存储当前搜索记录*/
            if (dto.getFromIndex()==0){
                ApUser user = AppThreadLocalUtils.getUser();
                if (user==null){
                    return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户不存在");
                }
                ApBehaviorEntry apBehaviorEntry = behaviorFeign.findApBehaviorEntry(user.getId(), dto.getEquipmentId());
                if (apBehaviorEntry==null){
                    return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"实体不存在");
                }
                apUserSearchService.insert(apBehaviorEntry.getId(),dto.getSearchWords());
            }

            SearchRequest searchRequest = new SearchRequest("app_info_article");

            SearchSourceBuilder searchSourceBuilder = new  SearchSourceBuilder();

           BoolQueryBuilder boolQueryBuilder= QueryBuilders.boolQuery();



                    /*组合一个 或 的查询条件*/
            QueryStringQueryBuilder queryStringQueryBuilder = QueryBuilders.queryStringQuery(dto.getSearchWords())
                    .field("title").field("content").defaultOperator(Operator.OR);

            boolQueryBuilder.must(queryStringQueryBuilder);

            /*查询一个 小于 条件*/
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime());

            boolQueryBuilder.filter(rangeQueryBuilder);


            searchSourceBuilder.query(boolQueryBuilder);


            /*分页*/
            searchSourceBuilder.from(dto.getPageNum());
            searchSourceBuilder.size(dto.getPageSize());

            /*排序*/
            searchSourceBuilder.sort("publishTime", SortOrder.DESC);


            searchRequest.source(searchSourceBuilder);

            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

            /*封装结果*/

            List<Map> list = new ArrayList<>();

            SearchHit[] hits = searchResponse.getHits().getHits();
            for (SearchHit hit : hits) {
                String sourceAsString = hit.getSourceAsString();//es 是 JSON形式的交互
                Map map = JSON.parseObject(sourceAsString, Map.class);
                list.add(map);
            }
            return ResponseResult.okResult(list);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"es查询错误");

    }
}
